package JMH.day02.atomicinteger;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class NoSyncInteger implements Runnable {

    private AtomicInteger x = new AtomicInteger(200);
    private static Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
//            synchronized (this) {
//            lock.lock();
//            try {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (x.get() > 0) {
                    int i = x.decrementAndGet(); // 使用原子类型的AtomicInteger，效率更高
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                } else {
                    System.exit(0);
                }
//            } finally {
//                lock.unlock();
//            }
//            }
        }
    }
}

class Go {

    public static void main(String[] args) {
        NoSyncInteger test = new NoSyncInteger();
        for (int i = 0; i < 4; i++) {
            new Thread(test).start();
        }
    }

}
